<template>
    <div class="app-container">
        <el-form :label-position="labelPosition" :rules="rules" ref="form" label-width="150px" :model="form">
            <el-form-item label="用户名">
                <el-input style="width:360px;" v-model="form.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="账号">
                <el-input style="width:360px;" v-model="form.loginId"></el-input>
            </el-form-item>
            <el-form-item label="旧密码" prop="oldLoginPwd">
                <el-input style="width:360px;" type="password" v-model="form.oldLoginPwd"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="loginPwd">
                <el-input style="width:360px;" type="password" v-model="form.loginPwd"
                    @input="validateBothPasswords"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="checkPass">
                <el-input style="width:360px;" type="password" v-model="form.checkPass"
                    @input="validateBothPasswords"></el-input>
            </el-form-item>
            <!-- 本网站个性头像 -->
            <el-form-item label="本网站个性头像">
                <upLoad ref="upLoad" v-model="form.src" />
            </el-form-item>

            <!-- 修改 -->
            <el-button style="margin-top:20px;" @click="submitForm" type="primary" plain>修改</el-button>
            <!-- 返回 -->
            <el-button type="danger" plain @click="resetForm">返回</el-button>
        </el-form>
    </div>
</template>

<script>
import * as admin_API from "@/api/user";
import upLoad from "@/components/UpLoad"
import { URL_CONFIG } from "@/urlConfig"
import { eventBus } from "@/eventBus"

export default {
    data() {
        // 验证新密码
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入新密码'));
            } else if (value.length < 6) {
                callback(new Error('密码长度至少6位'));
            } else {
                callback();
            }
        };
        // 验证确认密码
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.form.loginPwd) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };

        return {
            labelPosition: 'right',
            form: {
                id: '',
                name: '',//用户名
                loginId: '',//账号
                oldLoginPwd: '',//旧密码
                loginPwd: '',//新密码
                checkPass: '',//确认密码
                src: '',// 头像地址
            },
            rules: {
                oldLoginPwd: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' }
                ],
                loginPwd: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    { validator: validatePass2, trigger: 'blur' }
                ]
            },
            // isFormValid: false
        };
    },
    components: {
        upLoad,
    },
    created() {
        this.fetInfo();
    },
    methods: {
        async fetInfo() {
            try {
                const { data } = await admin_API.getInfo();
                this.form = data
                this.form.name = data.name;
                console.log(data, '开始拿数据');
            } catch (error) {
                console.error('获取用户信息失败:', error);
                this.$message.error('获取用户信息失败，请重试');
            }
        },
        validateBothPasswords() {
            // 当任意密码字段变化时，验证两个字段
            this.$refs.form.validateField('loginPwd');
            this.$refs.form.validateField('checkPass');

            // // 更新表单有效性状态（用于禁用/启用提交按钮）
            // this.$refs.form.validate(valid => {
            //     this.isFormValid = valid;
            // });
        },
        async submitForm() {

            if (this.form.name && this.form.oldLoginPwd && this.form.loginPwd) {
                // // 表单验证通过，提交数据
                // console.log('提交表单数据:', this.form);
                const data = await admin_API.putAdmin(this.form)
                if (typeof data === 'string') {
                    const result = JSON.parse(data)
                    console.log(result, '转成对象', this.$route, '路由');
                    this.$message.error(result.msg)
                } else {
                    // 说明修改成功
                    console.log(this.form, '修改后的form');

                    eventBus.$emit('update_avatar', this.form.src) // this.form.src 为上传后的头像URL

                    this.$message.success('修改成功，请重新登录')
                    await this.$store.dispatch('user/logout')
                    this.$router.push({
                        name: 'login',
                        query: {
                            redirect: this.$route.fullPath
                        }
                    }) // 退出页面回到登录页
                }
                console.log(data, "::查看是否正确");



                // // 调用API更新密码
                // admin_API.putAdmin({
                //     oldPassword: this.form.oldLoginPwd,
                //     newPassword: this.form.loginPwd
                // })
                //     .then(() => {
                //         this.$message.success('密码更新成功');
                //         this.resetForm();
                //     })
                //     .catch(error => {
                //         this.$message.error('密码更新失败: ' + error.message);
                //     });
            } else {
                console.log('表单验证失败');
                this.$message.error('必须填写所以项目')
                // return false;
            }
        },
        resetForm() {
            this.$router.push('/')

            // // 【重置表单】
            // this.$refs.form.resetFields();
            // this.form = {
            //     name: this.form.name, // 保留用户名
            //     oldLoginId: '',
            //     loginId: '',
            //     checkPass: ''
            // };
        }
    }
};
</script>

<style></style>